<template>
	<view class="dowload-apk">
		123123
		<u-modal v-model="isAppModule.show" :content="isAppModule.content" :show-cancel-button="true"
			@confirm="isAppModuleConfirm"></u-modal>
		<u-modal v-model="downloadModel.show" :title-style="{color: 'red'}" :show-confirm-button="false"
			:show-cancel-button="true" @cancel="downloadModelCancel">
			<view class="slot-content">
				<view>{{downloadModel.content}}</view>
				<!-- <rich-text :nodes="downloadModel.content"></rich-text> -->
			</view>
		</u-modal>
	</view>
</template>

<script>
	export default {
		name: "downloadApk",
		data() {
			return {
				isAppModule: {
					show: false,
					content: '检测到应用未安装，是否自动为您安装应用',
					downloadUrl: ''
				},
				_prg: 0,
				_showLoading: null,
				_dtask: null,
				downloadModel: {
					show: false,
					content: ''
				}
			};
		},
		methods: {
			isAppModuleConfirm() {
				console.log('isAppModuleConfirm1');
				let downloadApkUrl = this.isAppModule.downloadUrl
				console.log(this.isAppModule.downloadUrl);
				this._dtask = plus.downloader.createDownload(downloadApkUrl, {}, function(d, status) {
					console.log(status);
					// 下载完成  
					if (status == 200) {
						console.log(plus.io.convertLocalFileSystemURL(d.filename));
						plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), {}, {}, function(
							error) {
							uni.showToast({
								title: '安装失败',
								duration: 1500
							});
						})
					} else {
						uni.showToast({
							title: '更新失败',
							duration: 1500
						});
					}
				});
				// dtask.start();
				try {
					this._dtask.start(); // 开启下载的任务
					this._prg = 0;
					// this._showLoading = plus.nativeUI.showWaiting("正在下载"); //创建一个showWaiting对象 
					this.downloadModel.show = true
					this.downloadModel.content = '正在下载'
					this._dtask.addEventListener('statechanged', this.stateChanged, false);
				} catch (err) {
					console.log('错误信息', err)
					plus.nativeUI.closeWaiting();
				}
			},
			stateChanged(task, status) {
				// console.log(task.state);
				// console.log(this.prg);.
				// 给下载任务设置一个监听 并根据状态  做操作
				console.log(this.downloadModel.content);
				switch (task.state) {
					case 1:
						// this._showLoading.setTitle("正在下载");
						this.downloadModel.content = '正在下载'
						break;
					case 2:
						// this._showLoading.setTitle("已连接到服务器");
						this.downloadModel.content = '已连接到服务器'
						break;
					case 3:
						this._prg = parseInt((parseFloat(task.downloadedSize) / parseFloat(task.totalSize)) *
							100);
						// this._showLoading.setTitle("  正在下载" + this._prg + "%  ");
						this.downloadModel.content = "正在下载" + this._prg + "% "
						break;
					case 4:
						plus.nativeUI.closeWaiting();
						this.downloadModel.show = false
						//下载完成
						break;
				}
			},
			downloadModelCancel() {
				plus.downloader.clear();
			},
		}
	}
</script>

<style>

</style>
